package com.zhiwen.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zhiwen.config.DeepSeekConfig;
import com.zhiwen.domain.entity.Question;
import com.zhiwen.service.AiSearchService;
import com.zhiwen.service.QuestionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * AI搜索服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiSearchServiceImpl implements AiSearchService {

    private final DeepSeekConfig deepSeekConfig;
    private final QuestionService questionService;
    private final Gson gson = new Gson();

    /**
     * 智能搜索问题 使用缓存减少API调用
     */
    @Override
    @Cacheable(value = "aiSearch", key = "'question:' + #query + ':' + #limit", unless = "#result == null || #result.isEmpty()")
    public List<Map<String, Object>> searchQuestions(String query, Integer limit) {
        try {
            String prompt = "我需要搜索与以下问题相关的内容: " + query
                    + "\n请分析这个问题的核心意图，并给出" + limit + "个相关的搜索结果，"
                    + "返回JSON格式，包含title(标题)和content(简要内容)字段";

            String aiResponse = callDeepSeekApi(prompt);
            return parseAiSearchResults(aiResponse, limit);
        } catch (Exception e) {
            log.error("AI搜索问题失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取问题的智能推荐答案
     */
    @Override
    @Cacheable(value = "aiSearch", key = "'answer:' + #questionId", unless = "#result == null || #result.isEmpty()")
    public String getAnswerSuggestion(Long questionId) {
        System.out.println(questionId);
        try {
            Question question = questionService.getById(questionId);
            if (question == null) {
                return "问题不存在";
            }

            String prompt = "请针对以下问题给出一个专业、全面的回答建议: \n"
                    + "问题标题: " + question.getTitle() + "\n"
                    + "问题内容: " + question.getContent();

            return callDeepSeekApi(prompt);
        } catch (Exception e) {
            log.error("获取AI回答建议失败: {}", e.getMessage(), e);
            return "生成回答建议时出错，请稍后再试";
        }
    }

    /**
     * 根据关键词获取相关问题建议
     */
    @Override
    @Cacheable(value = "aiSearch", key = "'similar:' + #keyword + ':' + #limit", unless = "#result == null || #result.isEmpty()")
    public List<String> getSimilarQuestions(String keyword, Integer limit) {
        try {
            String prompt = "请根据关键词「" + keyword + "」，生成" + limit
                    + "个用户可能会提问的问题，返回JSON数组格式";

            String aiResponse = callDeepSeekApi(prompt);
            return parseAiSimilarQuestions(aiResponse, limit);
        } catch (Exception e) {
            log.error("获取AI相似问题失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    /**
     * 智能分析用户搜索意图
     */
    @Override
    public Map<String, Object> analyzeSearchIntent(String query) {
        try {
            String prompt = "请分析用户搜索查询「" + query + "」的意图，"
                    + "并返回JSON格式，包含以下字段：\n"
                    + "- mainIntent: 主要搜索意图\n"
                    + "- category: 可能的问题分类\n"
                    + "- keyTerms: 关键术语或概念(数组)\n"
                    + "- suggestedTags: 建议的标签(数组)";

            String aiResponse = callDeepSeekApi(prompt);
            return parseAiIntentAnalysis(aiResponse);
        } catch (Exception e) {
            log.error("分析搜索意图失败: {}", e.getMessage(), e);
            Map<String, Object> fallback = new HashMap<>();
            fallback.put("mainIntent", query);
            fallback.put("error", "分析失败");
            return fallback;
        }
    }

    /**
     * 调用DeepSeek API
     */
    private String callDeepSeekApi(String prompt) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(deepSeekConfig.getBaseUrl());

            // 设置超时
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(deepSeekConfig.getConnectTimeout())
                    .setSocketTimeout(deepSeekConfig.getRequestTimeout())
                    .build();
            httpPost.setConfig(requestConfig);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey());

            // 构建请求体
            JsonObject requestBody = new JsonObject();
            requestBody.addProperty("model", deepSeekConfig.getModel());
            requestBody.addProperty("max_tokens", deepSeekConfig.getMaxTokens());
            requestBody.addProperty("temperature", deepSeekConfig.getTemperature());

            JsonArray messages = new JsonArray();
            JsonObject message = new JsonObject();
            message.addProperty("role", "user");
            message.addProperty("content", prompt);
            messages.add(message);
            requestBody.add("messages", messages);

            // 设置请求体
            StringEntity stringEntity = new StringEntity(requestBody.toString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseString = EntityUtils.toString(entity);
                    JsonObject jsonResponse = gson.fromJson(responseString, JsonObject.class);

                    // 提取生成的文本
                    if (jsonResponse.has("choices") && !jsonResponse.getAsJsonArray("choices").isEmpty()) {
                        JsonObject choice = jsonResponse.getAsJsonArray("choices").get(0).getAsJsonObject();
                        if (choice.has("message") && choice.getAsJsonObject("message").has("content")) {
                            return choice.getAsJsonObject("message").get("content").getAsString();
                        }
                    }

                    return responseString;
                }
                return "无响应数据";
            }
        }
    }

    /**
     * 解析AI搜索结果
     */
    private List<Map<String, Object>> parseAiSearchResults(String aiResponse, Integer limit) {
        try {
            // 尝试直接解析JSON数组
            if (aiResponse.trim().startsWith("[")) {
                return gson.fromJson(aiResponse, List.class);
            }

            // 尝试从文本中提取JSON
            int startIndex = aiResponse.indexOf("[");
            int endIndex = aiResponse.lastIndexOf("]");

            if (startIndex >= 0 && endIndex > startIndex) {
                String jsonArray = aiResponse.substring(startIndex, endIndex + 1);
                return gson.fromJson(jsonArray, List.class);
            }

            // 如果无法解析JSON，返回单个结果
            List<Map<String, Object>> results = new ArrayList<>();
            Map<String, Object> result = new HashMap<>();
            result.put("title", "AI生成结果");
            result.put("content", aiResponse);
            results.add(result);

            return results;
        } catch (Exception e) {
            log.error("解析AI搜索结果失败: {}", e.getMessage(), e);
            List<Map<String, Object>> fallback = new ArrayList<>();
            Map<String, Object> result = new HashMap<>();
            result.put("title", "搜索结果");
            result.put("content", aiResponse);
            fallback.add(result);
            return fallback;
        }
    }

    /**
     * 解析AI相似问题结果
     */
    private List<String> parseAiSimilarQuestions(String aiResponse, Integer limit) {
        try {
            // 尝试直接解析JSON数组
            if (aiResponse.trim().startsWith("[")) {
                List<String> questions = gson.fromJson(aiResponse, List.class);
                return questions.stream().limit(limit).collect(Collectors.toList());
            }

            // 尝试从文本中提取JSON
            int startIndex = aiResponse.indexOf("[");
            int endIndex = aiResponse.lastIndexOf("]");

            if (startIndex >= 0 && endIndex > startIndex) {
                String jsonArray = aiResponse.substring(startIndex, endIndex + 1);
                List<String> questions = gson.fromJson(jsonArray, List.class);
                return questions.stream().limit(limit).collect(Collectors.toList());
            }

            // 如果无法解析JSON，尝试按行拆分
            String[] lines = aiResponse.split("\n");
            List<String> questions = new ArrayList<>();

            for (String line : lines) {
                line = line.trim();
                if (!line.isEmpty() && line.length() > 5) {
                    // 移除序号、引号和其他标记
                    line = line.replaceAll("^\\d+\\.\\s*", "").replaceAll("^[\"']|[\"']$", "");
                    questions.add(line);
                    if (questions.size() >= limit) {
                        break;
                    }
                }
            }

            return questions;
        } catch (Exception e) {
            log.error("解析AI相似问题失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    /**
     * 解析AI意图分析结果
     */
    private Map<String, Object> parseAiIntentAnalysis(String aiResponse) {
        try {
            // 尝试直接解析JSON对象
            if (aiResponse.trim().startsWith("{")) {
                return gson.fromJson(aiResponse, Map.class);
            }

            // 尝试从文本中提取JSON
            int startIndex = aiResponse.indexOf("{");
            int endIndex = aiResponse.lastIndexOf("}");

            if (startIndex >= 0 && endIndex > startIndex) {
                String jsonObject = aiResponse.substring(startIndex, endIndex + 1);
                return gson.fromJson(jsonObject, Map.class);
            }

            // 如果无法解析JSON，返回文本
            Map<String, Object> result = new HashMap<>();
            result.put("rawResponse", aiResponse);
            return result;
        } catch (Exception e) {
            log.error("解析AI意图分析失败: {}", e.getMessage(), e);
            Map<String, Object> fallback = new HashMap<>();
            fallback.put("error", "解析失败");
            fallback.put("rawResponse", aiResponse);
            return fallback;
        }
    }
}
